using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Mvvm;

namespace Byond.Frontend.ViewModels
{
	public class ModifiedDocumentsViewModel : ViewModelBase
	{
		private readonly IDocumentManager _documentManager;
		private readonly Func<DocumentModel, Action, ModifiedDocumentViewModel> _documentViewModelFactory;

		private void Ctor()
		{
			_documentManager.DirtyDocumentsChanged += UpdateDocuments;
		}

		public int NumberOfModifiedDocuments { get; private set; }

		private readonly ObservableCollection<ModifiedDocumentViewModel> _modifiedDocuments =
			new ObservableCollection<ModifiedDocumentViewModel>();
		public IEnumerable<ModifiedDocumentViewModel> ModifiedDocuments { get { return _modifiedDocuments; } }

		private bool _isPopupOpen;
		public bool IsPopupOpen
		{
			get { return _isPopupOpen; }
			set
			{
				_isPopupOpen = value;
				OnPropertyChanged("IsPopupOpen");
			}
		}

		public void ShowDocuments()
		{
			IsPopupOpen = true;
		}

		private void UpdateDocuments()
		{
			_modifiedDocuments.Clear();

			foreach (var it in _documentManager.DirtyDocuments)
				_modifiedDocuments.Add(_documentViewModelFactory(it, () => IsPopupOpen = false));

			NumberOfModifiedDocuments = _modifiedDocuments.Count;
			OnPropertyChanged("NumberOfModifiedDocuments");
		}
	}
}